package com.wandian.util;


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 *
 * @date 2011-09-26, 10:33:04
 * @author long@7road.com
 * @description ConvertUtil类：常用的类型之间转换，字符串转换数字，布尔类型
 * 
 */
public class ConvertUtil {

    private static Map<Class, Class> primitiveMap = new java.util.HashMap<Class, Class>();
    private static final Logger logger = LogManager.getLogger(ConvertUtil.class);

    static {
        primitiveMap.put(boolean.class, Boolean.class);
        primitiveMap.put(byte.class, Byte.class);
        primitiveMap.put(char.class, Character.class);
        primitiveMap.put(short.class, Short.class);
        primitiveMap.put(int.class, Integer.class);
        primitiveMap.put(long.class, Long.class);
        primitiveMap.put(float.class, Float.class);
        primitiveMap.put(double.class, Double.class);
    }

    /**
     * Best try to convert string to destination class. If destClass is one of
     * the supported primitive classes, an object of that type is returned. 
     * Otherwise, the original string is returned.
     */
    public static Object convert(String value, Class<?> destClass) {
        return convert(value, destClass, null);
    }

    public static Object convert(String value, Class<?> destClass, Object defaultvalue) {
        if ((value == null) || "".equals(value)) {
            return defaultvalue;
        }

        if (destClass.isPrimitive()) {
            destClass = primitiveMap.get(destClass);
        }

        try {
            Method m = destClass.getMethod("valueOf", String.class);
            int mods = m.getModifiers();
            if (Modifier.isStatic(mods) && Modifier.isPublic(mods)) {
                return m.invoke(null, value);
            }
        } catch (NoSuchMethodException e) {
            if (destClass == Character.class) {
                return Character.valueOf(value.charAt(0));
            }
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {
        }

        return value;
    }

    public static boolean toBoolean(String value, Object defaultvalue) {
        Object obj = convert(value, boolean.class, defaultvalue);
        return (Boolean) obj;
    }

    public static int toInt(String value) {

        return toInt(value, 0);
    }

    public static int toInt(String value, Object defaultvalue) {
        if (!StringUtil.isNumeric(value)) {
            return (Integer) defaultvalue;
        }
        Object obj = convert(value, int.class, defaultvalue);
        return (Integer) obj;
    }
}
